﻿using CI.Models.Production.Interfaces;

namespace CI.Models.Production
{
    public class QuantityCalculator<T> : ModelBase, IQuantityCalculator<T> where T : struct
    {
        private T _perRun;
        private int _runs;
        private T _total;
        private readonly bool _isPerRunEdittable;

        public QuantityCalculator(T perRun, int runs, bool isPerRunEdittable)
        {
            _isPerRunEdittable = isPerRunEdittable;
            _perRun = perRun;
            Runs = runs;
            UpdateTotalFromPerRunOrRuns();
            StartModel();
        }

        public QuantityCalculator(T perRun, int runs) : this(perRun, runs, false)
        {
        }

        #region IQuantityCalculator<T> Members

        public T PerRun
        {
            get { return _perRun; }
            set
            {
                if (!IsPerRunEdittable) throw new CannotEditException("You cannot edit the PerRun property");
                SetField(ref _perRun, value, () => PerRun, UpdateTotalFromPerRunOrRuns);
            }
        }

        public int Runs
        {
            get { return _runs; }
            set { SetField(ref _runs, value, () => Runs, UpdateTotalFromPerRunOrRuns); }
        }

        public T Total
        {
            get { return _total; }
            set { SetField(ref _total, value, () => Total, UpdateRunsFromTotal); }
        }

        public bool IsPerRunEdittable
        {
            get { return _isPerRunEdittable; }
        }

        #endregion

        protected void UpdateTotalFromPerRunOrRuns()
        {
            SetField(ref _total, Extensions.MultiplyByInt(PerRun, Runs), () => Total);
        }

        private void UpdateRunsFromTotal()
        {
            SetField(ref _runs, Extensions.FindIntegerFactor(PerRun, Total), () => Runs);
            UpdateTotalFromPerRunOrRuns();
        }
    }
}